package com.cn.yang.servlet;

import com.alibaba.fastjson.JSONObject;
import com.cn.yang.model.mainPage.HeadLinkModel;
import com.cn.yang.model.news.NewsClassifyModel;
import com.cn.yang.model.news.NewsModel;
import com.cn.yang.service.MainPageService;
import com.cn.yang.service.NewsService;
import com.cn.yang.service.impl.MainPageServiceImpl;
import com.cn.yang.service.impl.NewsServiceImpl;
import com.cn.yang.util.PageUtil;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/news")
public class DateNewsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        //获得headLink的List。
        MainPageService headLink = new MainPageServiceImpl();
        List<HeadLinkModel> list = headLink.selectHeadLink();
        
//===========================================================================================
        Integer type;
        String a = req.getParameter("type");
        if (a==null || a.equals(0)){
            type = null;
        }else {
            type = Integer.valueOf(a);
            Jedis jedis = new Jedis();
        }
        PageUtil pageUtil = new PageUtil();
        Integer pageNumber = (req.getParameter("pageNumber") == null ? 1 : Integer.valueOf(req.getParameter("pageNumber")));
        pageUtil.setPageNumber(pageNumber);
        pageUtil.setPageSize(8);
        NewsModel model = new NewsModel();
        model.setType(type);
        model.setPageUtil(pageUtil);
        NewsService service = new NewsServiceImpl();
        List<NewsModel> newslist = service.findNews(model);
        List<NewsClassifyModel> newsClassifylist = service.findClassify();
        int countNews = service.countNews(model);
        int countPage =  (int)Math.ceil(countNews/8.0);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list",list);
        jsonObject.put("newslist",newslist);
        jsonObject.put("countPage",countPage);
        jsonObject.put("newsClassifylist",newsClassifylist);
        resp.getWriter().println(jsonObject);

    }
}
